import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router'
// 对axios再封装
//创建request实例
const request = axios.create({
    baseURL: "/api",
    timeout: 600000
});

//处理axios的响应结果
request.interceptors.response.use((response)=>{
    return response.data;
}, (error)=>{
    if(error.response.status==401){
        ElMessage.error("登录失败，请重新登录");
        router.push('/login');
    }
    return Promise.reject(error);
});

// 让每次请求都携带token
request.interceptors.request.use((config)=>{
    // 从localStorage中获取token值
    const loginInfoStr = localStorage.getItem("loginInfo");
    if(loginInfoStr){
        const loginInfo = JSON.parse(loginInfoStr);
        console.log(loginInfo)
        // 自定义请求头
        config.headers.token = loginInfo.token;
    }
    return config;
    
});

export default request;